<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="disLook ? '查看' : form.dd_id ? '编辑' : '添加'"
    v-model="visible"
    align-center
    width="90%"
    destroy-on-close
  >
    <div class="w-full">
      <div class="v-title mb-3">基础信息</div>
      <el-form
        ref="formRef"
        :model="form"
        label-position="top"
        :label-width="140"
        :disabled="disLook"
      >
        <div class="grid grid-cols-4 gap-x-3">
          <el-form-item label="开发需求单号">
            <el-input
              v-model.lazy="form.develop_no"
              placeholder="请输入"
              disabled
            />
          </el-form-item>
          <el-form-item label="申请人员">
            <el-input
              :value="form.create_user"
              placeholder="请选择"
              disabled
              class="w-full"
            />
          </el-form-item>
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="form.create_time"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="w-full"
              disabled
            />
          </el-form-item>
          <el-form-item label="申请部门">
            <el-input
              :value="form.create_department_name"
              placeholder="请选择"
              disabled
              class="w-full"
            />
          </el-form-item>

          <el-form-item
            label="新品类型"
            prop="develop_type"
            :rules="[
              { required: true, message: '不能为空', trigger: 'change' },
            ]"
          >
            <el-radio-group v-model="form.develop_type">
              <el-radio
                :value="item.value"
                v-for="item in options.develop_type"
                :key="item"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="需求类型"
            prop="demand_type"
            :rules="[
              { required: true, message: '不能为空', trigger: 'change' },
            ]"
          >
            <el-radio-group
              v-model="form.demand_type"
              @change="handleDemandType"
            >
              <el-radio
                :value="item.value"
                v-for="item in options.demand_type"
                :key="item"
                >{{ item.label }}</el-radio
              >
            </el-radio-group></el-form-item
          >
          <el-form-item label="计划人员">
            <VCascader
              v-model="form.plan_user_id"
              placeholder="请选择人员"
              class="w-full"
              :disabled="!isEdit"
            />
          </el-form-item>
          <el-form-item label="飞书审核">
            <el-switch
              v-model="form.is_feishu_audit"
              inline-prompt
              active-text="是"
              inactive-text="否"
              :active-value="2"
              :inactive-value="1"
            /><span class="text-[#48b670] ml-[8px]"
              >提示:启用后只能在飞书审核</span
            >
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="w-full">
      <div class="v-title mb-3">产品信息</div>
      <div class="mb-3">
        <el-button
          type="primary"
          @click="() => goodsRef.open()"
          :disabled="disLook"
          ><i class="dk-iconfont icon-Plus" />添加sku</el-button
        >
        <el-button
          v-if="!isEdit"
          type="danger"
          @click="() => (form.sku = [])"
          :disabled="disLook"
          >批量移除</el-button
        >
      </div>
      <el-form
        ref="formTableRef"
        :model="form"
        :validate-on-rule-change="false"
        :label-width="0"
        :disabled="disLook"
      >
        <vxe-table
          ref="tableRef"
          :data="form.sku"
          :max-height="479"
          show-overflow
          :rowConfig="{ height: 154 }"
          :scroll-y="{ enabled: true, gt: 10 }"
          size="small"
        >
          <vxe-column type="checkbox" :width="40" fixed="left"></vxe-column>
          <vxe-column title="图片" :min-width="100">
            <template #default="{ row }">
              <VImage :src="row.main_img" size="80px"></VImage>
            </template>
          </vxe-column>
          <vxe-column title="商品信息" :min-width="130">
            <template #default="{ row }">
              <VText title="sku" :value="row.sku" type="link">
                <el-link type="primary">{{ row.sku }}</el-link>
              </VText>
              <div class="font-bold text-red-600">
                装箱数:{{ row.packing_qty }}
              </div>
              <VText :value="row.is_combination_name" title="组合sku" />
            </template>
          </vxe-column>
          <vxe-column
            title="产品名称"
            :min-width="100"
            field="sku_cn_title"
          ></vxe-column>
          <vxe-column
            title="产品分类"
            :min-width="100"
            field="attribute_name"
          ></vxe-column>
          <vxe-column title="平台" :min-width="130">
            <template #default="{ row }">
              <VSelect
                v-model="row.platform"
                :options="options.platform"
                select
                placeholder="平台"
                class="w-full"
              />
            </template>
          </vxe-column>
          <vxe-column :min-width="180">
            <template #header>
              <div><span class="text-red-600">*</span> 总需求数量</div>
              <div><span class="text-red-600">*</span> 销售</div>
            </template>
            <template #default="{ row, rowIndex }">
              <div class="grid gap-1 p-1">
                <el-form-item
                  :prop="['sku', rowIndex, 'develop_num']"
                  label=""
                  :rules="[
                    { required: true, message: '不能为空', trigger: 'change' },
                  ]"
                  class="w-full mb-3"
                >
                  <el-input-number
                    v-model="row.develop_num"
                    :controls="false"
                    :min="0"
                    :step="1"
                    :precision="0"
                    placeholder="需求数量"
                    class="w-full"
                  />
                </el-form-item>
                <el-form-item
                  :prop="['sku', rowIndex, 'sale_id']"
                  label=""
                  :rules="[
                    { required: true, message: '不能为空', trigger: 'change' },
                  ]"
                  class="w-full"
                >
                  <VCascader
                    v-model="row.sale_id"
                    placeholder="请选择人员"
                    class="w-full"
                  />
                </el-form-item>
              </div>
            </template>
          </vxe-column>
          <vxe-column :min-width="140">
            <template #header>
              <div class="ml-[10px]" v-if="form.demand_type == 2">Asin</div>
              <div><span class="text-red-600">*</span> 新品状态</div>
            </template>
            <template #default="{ row, rowIndex }">
              <div class="grid gap-1 p-1">
                <el-input
                  v-if="form.demand_type == 2"
                  v-model="row.asin"
                  placeholder="asin"
                  class="w-full mb-3"
                ></el-input>
                <el-form-item
                  :prop="['sku', rowIndex, 'develop_status']"
                  label=""
                  :rules="[
                    { required: true, message: '不能为空', trigger: 'change' },
                  ]"
                  class="w-full"
                >
                  <VSelect
                    v-model="row.develop_status"
                    :options="develop_status_opt"
                    class="w-full"
                    placeholder="新品状态"
                  />
                </el-form-item>
              </div>
            </template>
          </vxe-column>
          <vxe-column :min-width="150">
            <template #header>
              <div><span class="text-red-600">*</span>国家</div>
              <div>
                <span class="text-red-600" v-if="form.demand_type == 1">*</span
                >目的仓
              </div>
            </template>
            <template #default="{ row, rowIndex }">
              <div class="grid gap-1 p-1 mb-3">
                <el-form-item
                  :prop="['sku', rowIndex, 'country']"
                  label=""
                  :rules="[
                    { required: true, message: '不能为空', trigger: 'change' },
                  ]"
                  class="mb-3"
                >
                  <VSelect
                    v-model="row.country"
                    :options="options.country"
                    class="w-full"
                    placeholder="国家"
                  />
                </el-form-item>
                <template v-if="form.demand_type == 1">
                  <el-form-item
                    :prop="['sku', rowIndex, 'country']"
                    label=""
                    :rules="[
                      {
                        required: true,
                        message: '不能为空',
                        trigger: 'change',
                      },
                    ]"
                    class="mb-3"
                  >
                    <VSelect
                      v-model="row.destination_warehouse"
                      :options="
                        row.country == 'US'
                          ? options.platform_destination_warehouse
                          : options.destination_warehouse
                      "
                      class="w-full"
                      filterable
                      clearable
                      placeholder="目的仓"
                    />
                  </el-form-item>
                </template>
                <template v-else>
                  <el-form-item label="" class="mb-3">
                    <VSelect
                      v-model="row.destination_warehouse"
                      :options="
                        row.country == 'US'
                          ? options.platform_destination_warehouse
                          : options.destination_warehouse
                      "
                      class="w-full"
                      filterable
                      clearable
                      placeholder="目的仓"
                    />
                  </el-form-item>
                </template>
              </div>
            </template>
          </vxe-column>
          <vxe-column :min-width="150">
            <template #header>
              <div><span class="text-red-600">*</span>需求交货日期</div>
              <div><span class="text-red-600">*</span>预计运输方式</div>
            </template>
            <template #default="{ row, rowIndex }">
              <div class="grid gap-1 p-1 mb-3">
                <el-form-item
                  :prop="['sku', rowIndex, 'develop_time']"
                  label=""
                  :rules="[
                    { required: true, message: '不能为空', trigger: 'change' },
                  ]"
                  class="mb-3"
                >
                  <el-date-picker
                    v-model="row.develop_time"
                    type="date"
                    value-format="YYYY-MM-DD"
                    class="w-full"
                    placeholder="需求交货日期"
                  />
                </el-form-item>
                <el-form-item
                  :prop="['sku', rowIndex, 'transport_type']"
                  label=""
                  :rules="[
                    { required: true, message: '不能为空', trigger: 'change' },
                  ]"
                  class="mb-3"
                >
                  <VSelect
                    v-model="row.transport_type"
                    :options="options.transport_type"
                    class="w-full"
                    placeholder="预计运输方式"
                  />
                </el-form-item>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="备注" min-width="120">
            <template #default="{ row }">
              <el-input
                v-model="row.remark"
                placeholder="备注"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 5 }"
                :maxlength="300"
              />
            </template>
          </vxe-column>
          <vxe-column title="操作" fixed="right" :width="110">
            <template #default="{ row, rowIndex }">
              <el-button link type="primary" @click="handleRemove(rowIndex)"
                >移除</el-button
              >
              <el-button
                v-if="!isEdit"
                link
                type="primary"
                @click="handleCopy(row, rowIndex)"
                >复制</el-button
              >
            </template>
          </vxe-column>
        </vxe-table>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="handleClose(false)">取 消</el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="save(1)"
        v-if="!disLook"
        >提 交</el-button
      >
      <el-button
        type="primary"
        :loading="loading"
        @click="save(2)"
        v-if="!disLook"
        >保 存</el-button
      >
    </template>
    <aGoods ref="goodsRef" @change="goodsChange" />
  </el-dialog>
</template>
<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus";
import XEUtils from "xe-utils";
import aGoods from "@/components/Goods";
import {
  purchaseDemandDetail,
  purchaseDemandCreate,
  purchaseDemandEdit,
} from "../../api.js";
const props = defineProps({
  options: { type: Object, default: () => ({}) },
});
const { options } = toRefs(props);
const emit = defineEmits(["close", "success"]);
const goodsRef = ref();
const loading = ref(false);
const visible = ref(false);
const form = ref({
  develop_type: null,
});
const isEdit = computed(() => !!form.value?.dd_id);
// 打开弹窗
const disLook = ref(false);
const open = async (id, isLook) => {
  visible.value = true;
  const { userInfo } = window;
  disLook.value = isLook ? true : false;
  form.value = {
    dd_id: id,
    create_user_id: userInfo?.user?.user_id,
    create_user: userInfo?.user?.en_name,
    create_time: XEUtils.toDateString(new Date(), "yyyy-MM-dd HH:mm:ss"),
    create_department_id: userInfo?.departments[0]?.department_id,
    create_department_name: userInfo?.departments[0]?.name,
    sku: [],
    demand_type: 1,
    develop_type: 2,
    is_feishu_audit: 2,
  };
  if (id) {
    getDetail(id);
  }
};
const getDetail = async (id) => {
  const { data } = await purchaseDemandDetail({ dd_id: id });
  form.value = data || {};
  form.value.sku = [JSON.parse(JSON.stringify(data))] || [];
};
const goodsChange = (val) => {
  if (!isEdit) {
    form.value.sku = val?.length > 1 ? [val[0]] : val || [];
  } else {
    form.value.sku =
      Array.isArray(val) && val.length > 20 ? val.slice(0, 20) : val;
  }
  // form.value.sku = val?.length > 1 ? [val[0]] : val || [];
};
const develop_status_opt = ref([]);
watch(
  () => [form.value.demand_type, options.value?.develop_status],
  ([develop_type, develop_status]) => {
    const obj = {
      2: new Set([1, 2, 3, 5]),
      1: new Set([2, 3, 4, 5]),
    };
    const validValues = obj[develop_type] ?? new Set();
    develop_status_opt.value = (develop_status ?? []).filter((item) =>
      validValues.has(item.value)
    );
  },
  { immediate: true }
);

const handleDemandType = (val) => {
  form.value.sku = form.value.sku.map((item) => ({
    ...item,
    develop_status: null,
    asin: val == 1 ? "" : item.asin,
  }));
};

const handleRemove = (ind) => {
  if (!isEdit) {
    form.value.sku = [];
  } else {
    form.value.sku.splice(ind, 1);
  }
};

const handleCopy = (row, ind) => {
  const obj = { ...row };
  form.value.sku.splice(ind + 1, 0, obj);
};
const formRef = ref();
const formTableRef = ref();
const save = async (is_submit, is_skip = undefined) => {
  const validator = await formRef?.value?.validate();
  const validatorTable = await formTableRef?.value?.validate();
  if (!validator || !validatorTable)
    return ElMessage.warning("必填项不能为空!");
  if (!form.value?.sku.length)
    return ElMessage.warning("请至少添加一条产品信息!");
  const { develop_type, demand_type, plan_user_id, dd_id, is_feishu_audit } =
    form.value;
  const basic = { develop_type, demand_type, plan_user_id, is_feishu_audit };
  const skuData = form.value.sku?.map(
    ({
      develop_num,
      sku,
      asin,
      remark,
      sale_id,
      develop_status,
      transport_type,
      develop_time,
      country,
      destination_warehouse,
      platform,
    }) => ({
      develop_num,
      sku,
      asin,
      remark,
      sale_id,
      develop_status,
      transport_type,
      develop_time,
      country,
      destination_warehouse,
      platform,
    })
  );
  let obj = dd_id
    ? {
        dd_id,
        ...basic,
        ...skuData[0],
        is_submit,
        is_skip,
      }
    : {
        basic: {
          ...basic,
          is_submit,
          is_skip,
        },
        sku: skuData,
      };
  try {
    loading.value = true;
    const { code, data, message } = await (obj?.dd_id
      ? purchaseDemandEdit
      : purchaseDemandCreate)(obj);
    const { is_skip } = data;
    if (code == 200) {
      ElMessage.success(obj?.dd_id ? "编辑成功" : "添加成功");
      handleClose(true);
      return;
    }
    if (is_skip === 2) {
      ElMessageBox.confirm(message, "提示", {
        type: "error",
        confirmButtonText: "是",
        cancelButtonText: "否",
      }).then((res) => {
        save(is_submit, 2);
      });
    } else {
      ElMessage.error(message);
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const handleClose = (refresh) => {
  visible.value = false;
  form.value = { develop_type: null };
  formRef?.value?.resetFields();
  emit("close");
  refresh && emit("success");
};
defineExpose({ open });
</script>
<style lang="scss" scoped></style>
